from typing import Optional
import os

from fastapi import APIRouter,status
from fastapi.responses import FileResponse
from fastapi.exceptions import HTTPException

from app.robot import RobotFile,RobotBizException

file_app = APIRouter()

@file_app.get("/log/{pid}/{file_date}")
def get_log_files(pid:str,file_date:str):
    """
    :param file_date: 日志文件日期 yyyyMMdd
    :param pid: 机器人实例ID,  * 表示所有实例
    :return: 日志zip文件
    """
    try:
        zipfile = RobotFile.get_log_file(pid,file_date)
        return FileResponse(path=zipfile, filename=os.path.basename(zipfile))
    except RobotBizException as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))


@file_app.get("/log/filter")
def get_filter_log_files(content:str,file_date_start:str,file_date_end:str, pid:Optional[str]=None):
    """
    查找含有给定content的日志文件
    :param content: 查找内容
    :param pid: 机器人实例ID
    :param file_date: 文件日期 yyyyMMdd
    :return:
    """

    try:
        zipfile = RobotFile.get_filter_log_files(content,file_date_start,file_date_end,pid)
        return FileResponse(path=zipfile, filename=os.path.basename(zipfile))
    except RobotBizException as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))



@file_app.get("/task/{pid}/{task_id}")
def get_task(pid: str, task_id: str):
    """
    获取指定ID的任务文件
    :param pid: 机器人实例名, *表示所有实例下查找
    :param task_id: 任务ID
    :return:
    """

    try:
        zipfile = RobotFile.get_task(pid,task_id)
        return FileResponse(path=zipfile, filename=os.path.basename(zipfile))
    except RobotBizException as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))

